<template>
  <el-dialog
    :title="fileName"
    width="1000px"
    append-to-body
    :visible.sync="visible"
    :before-close="handleClose"
  >
    <el-scrollbar class="scroll" v-loading="pdfLoading">
      <vue-office-pdf
        :src="fileUrl"
        @rendered="renderedHandler"
        @error="errorHandler"
        v-if="fileUrlType === 'pdf'"
      />
      <vue-office-docx
        :src="fileUrl"
        @rendered="renderedHandler"
        @error="errorHandler"
        v-if="fileUrlType === 'word'"
      />
      <div class="img-box">
        <img class="img" v-if="fileUrlType === 'img'" :src="fileUrl" />
      </div>
    </el-scrollbar>
  </el-dialog>
</template>

<script>
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import { judgeFileType } from "@/utils/judgeFileType";
export default {
  components: {
    VueOfficePdf,
    VueOfficeDocx,
  },
  props: {
    fileUrl: {
      type: String,
      required: true,
    },
    fileName: {
      type: String,
      required: true,
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.pdfLoading = true;
        this.fileUrlType = judgeFileType(this.fileUrl);
        if (this.fileUrlType === "img") {
          this.pdfLoading = false;
        }
      }
    },
  },
  data() {
    return {
      fileUrlType: "",
      pdfLoading: false,
    };
  },
  methods: {
    handleClose() {
      this.$emit("update:visible", false);
    },
    renderedHandler() {
      this.pdfLoading = false;
    },
    errorHandler() {
      this.$message.info("pdf正在渲染中...");
      this.pdfLoading = false;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .vue-office-pdf-wrapper {
  background: #fff !important;
}
::v-deep .docx-wrapper {
  background: #fff !important;
}
::v-deep .el-dialog__body {
  padding: 0;
}
.scroll {
  height: 500px;
  .img-box {
    padding: 14px;
    text-align: center;
    .img {
      margin: 0 auto;
      max-width: 100%;
      height: auto;
    }
  }
}
</style>
